<?php
declare (strict_types=1);

namespace app\common\model;

use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;

/**
 *
 * create_time: 2021-10-15 15:35:33
 * @property int $id
 * @property string $config_key 配置key
 * @property string $config_value 配置值
 * @property int $encode 是否json
 * @property string $create_time 创建时间  默认值 CURRENT_TIMESTAMP
 * @property string $update_time 更新时间  默认值 CURRENT_TIMESTAMP
 * @property string $delete_time 删除时间
 * @mixin \think\Model
 */
class Config extends BaseModel
{
    /**
     * @var array
     */
    private static $config;

    /**
     * 获取配置信息
     * @param $key
     * @param bool $fromCache
     * @return mixed|null
     */
    public static function get($key, $fromCache = true)
    {
        if ($fromCache && self::$config === null) {
            try {
                (new Config)->newQuery()->select()->each(

                    function ($item) {
                        if ($item->encode) {
                            $item->config_value = json_decode($item->config_value, true);
                        }
                        self::$config[$item->config_key] = $item->config_value;
                    });
            } catch (DataNotFoundException $e) {
            } catch (ModelNotFoundException $e) {
            } catch (DbException $e) {
            }
        }
        if (isset(self::$config[$key])) {
            return self::$config[$key];
        }
        return null;
    }

    /**
     * 更新配置
     * @param $key
     * @param $value
     * @return bool
     */
    public static function store($key, $value)
    {
        if (self::get($key) === null) {
            return false;
        }
        self::$config[$key] = $value;
        if (is_array($value) || is_object($value)) {
            $value = json_encode($value, JSON_UNESCAPED_UNICODE);
        }
        (new Config)->where('config_key', $key)->update(['config_value' => $value]);
        return true;
    }

    /**
     * 安全更新，没有就创建
     * @param $key
     * @param $value
     * @return bool
     */
    public static function safeStore($key, $value)
    {
        if (self::get($key, false) === null) {
            self::$config[$key] = $value;
            $encode = 0;
            if (is_array($value) || is_object($value)) {
                $encode = 1;
                $value = json_encode($value, JSON_UNESCAPED_UNICODE);
            }
            (new Config())->create([
                'config_key' => $key,
                'config_value' => $value,
                'encode' => $encode
            ]);
            return true;
        }
        return self::store($key, $value);
    }
}
